<?php
namespace app\admin\model;
use think\Model;
use app\admin\model\Networks;
class Carts extends Model
{	
	public static function addData($user_id,$data=array()){
		$base['create_time'] = time();
		$base['user_id'] = $user_id;
		$base['value'] = serialize($data);
		if(isset($data['cart_id']) && $data['cart_id'] > 0){
			self::where('user_id',$user_id)->where('id',$data['cart_id'])->delete();
		}
		$id = (int)self::insertGetId($base);
		return $id > 0 ? $id : 0; 
	}
	public static function deleteAll($user_id,$cat_id=0){
		$map['user_id'] = $user_id;
		if($cat_id > 0){
			$map['id'] = $cat_id;
		}else{
			$map['create_time'] = array('lt',time()-86400);
		}
		return self::where($map)->delete();
	}
	public static function getCartData($user_id){
		$carts = self::where('user_id',$user_id)->select();
        $data = [];
        if($carts){
        	$Networks = new Networks;
            foreach($carts as $cart){
                $base = unserialize($cart['value']);
                $base['_id'] = $cart['id'];
                $data[] = $Networks->setDataLabel($base);
            }
        }
        return $data;
	}
	public static function getNetworkData($id,$user_id){
		$row = self::where('user_id',$user_id)->where('id',$id)->find();
		return isset($row['value']) ? unserialize($row['value']): null;
	}
}